package com.estronger.shopmanage.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;

public class FileUtil {

	public static String saveFile(Context c, String fileName, Bitmap bitmap) {
		if(bitmap==null){
			return null;
		}
		return saveFile(c, "", fileName, bitmap);
	}

	public static String saveFile(Context c, String filePath, String fileName,
			Bitmap bitmap) {
		byte[] bytes = bitmapToBytes(bitmap);
		return saveFile(c, filePath, fileName, bytes);
	}

	public static byte[] bitmapToBytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(CompressFormat.JPEG, 100, baos);
		return baos.toByteArray();
	}

	public static String saveFile(Context c, String filePath, String fileName,
			byte[] bytes) {
		String fileFullName = "";
		FileOutputStream fos = null;
		String dateFolder = new SimpleDateFormat("yyyyMMdd", Locale.CHINA)
				.format(new Date());
		try {
			String suffix = "";
			if (filePath == null || filePath.trim().length() == 0) {
				filePath = Environment.getExternalStorageDirectory()
						+ "/JiaXT/" + dateFolder + "/";
			}
			File file = new File(filePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			File fullFile = new File(filePath, fileName + suffix);
			fileFullName = fullFile.getPath();
			fos = new FileOutputStream(new File(filePath, fileName + suffix));
			fos.write(bytes);
		} catch (Exception e) {
			fileFullName = "";
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					fileFullName = "";
				}
			}
		}
		return fileFullName;
	}

	/**
	 * @param pathandname
	 *            文件的绝对路径
	 * @return 文件名
	 */
	public static String getFileName(String pathandname) {
		if (TextUtils.isEmpty(pathandname)) {
			return "";
		}
		int start = pathandname.lastIndexOf("/");
		if (start < 1)
			start = pathandname.lastIndexOf("\\");
		int end = pathandname.length();
		if (start != -1 && end != -1) {
			return pathandname.substring(start + 1, end);
		} else {
			return null;
		}
	}

	/**
	 * @param pathandname
	 *            文件的绝对路径
	 * @return 文件名
	 */
	public static String getFileName2(String pathandname) {
		if (TextUtils.isEmpty(pathandname)) {
			return "";
		}
		int start = pathandname.lastIndexOf("\\");
		int end = pathandname.length();
		if (start != -1 && end != -1) {
			return pathandname.substring(start + 1, end);
		} else {
			return null;
		}
	}

	public static String getFileRealPath(Activity mContext, Intent data) {
		if (data == null) {
			// 用户未选择任何文件，直接返回
			return "";
		}
		String filePath = "";
		Uri uri = data.getData(); // 获取用户选择文件的URI
		if ("file".equalsIgnoreCase(uri.getScheme())){//使用第三方应用打开
			filePath = uri.getPath();
		}else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
			filePath = getPathByUri4kitkat(mContext, uri);
		} else {//4.4以下下系统调用方法
			filePath = getRealPathFromURI(mContext, uri);
		}
		if(TextUtils.isEmpty(filePath))  filePath = data.getDataString();
		if(TextUtils.isEmpty(filePath)) return "";
		String fname = "";
		if (filePath == null || filePath.length() == 0) {
			Toast.show(mContext, "附件路径为空!", Toast.LENGTH_SHORT);
			return "";
		}
		try {
			filePath = URLDecoder.decode(filePath, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if (!filePath.startsWith("/storage") && filePath.contains("emulated/0/")) {
			String rPath = filePath.substring(filePath.indexOf("/emulated/0/"));
			filePath = "/storage" + rPath;
		}
		return filePath;
	}

	public static String getRealPathFromURI(Context context, Uri contentUri) {
		String res = null;
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
		if(null!=cursor&&cursor.moveToFirst()){
			int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			res = cursor.getString(column_index);
			cursor.close();
		}
		return res;
	}

	@SuppressLint("NewApi")
	public static String getPathByUri4kitkat(final Context context, final Uri uri) {
		try {
			final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
			if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
				if (isExternalStorageDocument(uri)) {// ExternalStorageProvider
					final String docId = DocumentsContract.getDocumentId(uri);
					final String[] split = docId.split(":");
					final String type = split[0];
					if ("primary".equalsIgnoreCase(type)) {
						return SDCardUtil.SDCardRoot + split[1];
					}
				} else if (isDownloadsDocument(uri)) {// DownloadsProvider
					final String id = DocumentsContract.getDocumentId(uri);
					if(id.startsWith("raw:")) {
						return id.substring(id.indexOf(":")+1);
					}
					final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
							Long.valueOf(id));
					return getDataColumn(context, contentUri, null, null);
				} else if (isMediaDocument(uri)) {// MediaProvider
					final String docId = DocumentsContract.getDocumentId(uri);
					final String[] split = docId.split(":");
					final String type = split[0];
					Uri contentUri = null;
					if ("image".equals(type)) {
						contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
					} else if ("video".equals(type)) {
						contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
					} else if ("audio".equals(type)) {
						contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
					}
					final String selection = "_id=?";
					final String[] selectionArgs = new String[] { split[1] };
					return getDataColumn(context, contentUri, selection, selectionArgs);
				}
			} else if ("content".equalsIgnoreCase(uri.getScheme())) {// MediaStore
				// (and
				// general)
				return getDataColumn(context, uri, null, null);
			} else if ("file".equalsIgnoreCase(uri.getScheme())) {// File
				return uri.getPath();
			}
		}catch (Exception e){
			e.fillInStackTrace();
		}
		return null;
	}

	public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
		Cursor cursor = null;
		final String column = "_data";
		final String[] projection = { column };
		try {
			try{
				cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
			}catch (Exception e) {}
			if (cursor != null && cursor.moveToFirst()) {
				try {
					final int column_index = cursor.getColumnIndexOrThrow(column);
					return cursor.getString(column_index);
				}catch (Exception e){}
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri.getAuthority());
	}

	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	}

	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri.getAuthority());
	}
}
